package com.zhixing.web.common.utils;

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

/**
 * @author dzh
 * @version 1.0.0.05020
 * <p>project: d-blog</p>
 * <p>created time: 2022/05/02 15:17</p>
 * <p>describe: 文件上传工具类</p>
 * <p>remarks: </p>
 **/
public class FileUtil {

    public static String uploadFile(MultipartFile file, String filePath, boolean setExpire) throws Exception {

        String fileName = file.getOriginalFilename();

        String extension = FilenameUtils.getExtension(fileName);

        fileName = UUID.randomUUID().toString().replace("-", "") + "." + extension;

        if (setExpire) {

            fileName = "temp_" + fileName;
        }

        File targetFile = new File(filePath);

        if(!targetFile.exists()) {

            //noinspection ResultOfMethodCallIgnored
            targetFile.mkdirs();
        }

        FileOutputStream out = new FileOutputStream(filePath + fileName);

        out.write(file.getBytes());

        out.flush();

        out.close();

        return fileName;
    }

}
